﻿using System.Windows;
using Microsoft.Phone.Controls;

namespace RxLocationService
{
    using System;
    using System.Device.Location;
    using System.Reactive.Linq;
    using WP7Contrib.Collections;
    using WP7Contrib.Services.Location;

    public partial class MainPage : PhoneApplicationPage
    {
        private readonly ILocationService locationService = new LocationService(GeoPositionAccuracy.Default);
        
        private readonly ObservableCollection<string> results = new ObservableCollection<string>();

        private IDisposable locationSubscriber;
        private IDisposable currentSubscriber;

        // Constructor
        public MainPage()
        {
            InitializeComponent();
            this.locationResults.ItemsSource = results;
            this.threshold.Text = "5";
        }

        private void startDistance_Click(object sender, RoutedEventArgs e)
        {
            if (locationSubscriber != null)
            {
                locationSubscriber.Dispose();
            }

            var val = Convert.ToInt32(this.threshold.Text);
            locationSubscriber = locationService.LocationByDistanceThreshold(val)
                .ObserveOnDispatcher()
                .Subscribe(location => this.results.Insert(0, string.Format("'{0}', '{1}'", location.Latitude, location.Longitude)));
        }

        private void startTime_Click(object sender, RoutedEventArgs e)
        {
            if (locationSubscriber != null)
            {
                locationSubscriber.Dispose();
            }

            var val = (int)(Convert.ToDouble(this.threshold.Text) * 1000);
            locationSubscriber = locationService.LocationByTimeThreshold(TimeSpan.FromMilliseconds(val), GeoPositionAccuracy.Default)
                .ObserveOnDispatcher()
                .Subscribe(location => this.results.Insert(0, string.Format("'{0}', '{1}'", location.Latitude, location.Longitude)));
        }

        private void stop_Click(object sender, RoutedEventArgs e)
        {
            if (locationSubscriber == null)
                return;

            results.Clear();

            locationSubscriber.Dispose();
            locationSubscriber = null;
        }

        private void currentLocation_Click(object sender, RoutedEventArgs e)
        {
            if (currentSubscriber != null)
            {
                currentSubscriber.Dispose();
            }

            currentSubscriber = locationService.Location(GeoPositionAccuracy.High).Subscribe(location => this.results.Insert(0,
                                                                                 string.Format("'{0}', '{1}'",
                                                                                               location.Latitude,
                                                                                               location.Longitude)));
        }
    }
}